<template>
  <div class="flex flex-col">
    <!-- 搜索和筛选区域 -->
    <div class="flex justify-between">
      <el-form :model="searchForm" inline label-width="80px">
        <el-form-item label="用户名">
          <el-input
            v-model="searchForm.username"
            placeholder="请输入用户名"
            clearable
            class="w-48"
          />
        </el-form-item>
        <el-form-item label="昵称">
          <el-input v-model="searchForm.nickname" placeholder="请输入昵称" clearable class="w-48" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
        <el-form-item> </el-form-item>
      </el-form>
      <el-button
        v-permission="['system:user:add']"
        type="primary"
        @click="handleCreateUser"
        :icon="Plus"
      >
        新增用户
      </el-button>
    </div>
    <!-- 用户列表 -->
    <div class="flex h-0 grow flex-col">
      <el-table
        class="grow"
        v-loading="loading"
        :data="userList.list"
        border
        stripe
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="用户ID" width="80" />
        <el-table-column prop="username" label="用户名" />
        <el-table-column prop="nickname" label="昵称" />
        <el-table-column prop="email" label="邮箱" />
        <el-table-column prop="phone" label="手机号" />
        <el-table-column prop="status" label="状态" width="80">
          <template #default="scope">
            <el-switch
              v-model="scope.row.status"
              :active-value="1"
              :inactive-value="0"
              @change="handleStatusChange(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="创建时间" width="180" show-overflow-tooltip />
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="scope">
            <el-button
              v-permission="['system:user:edit']"
              type="primary"
              link
              @click="handleEditUser(scope.row)"
              class="mr-2"
            >
              编辑
            </el-button>
            <el-button
              v-permission="['system:user:edit']"
              type="primary"
              link
              @click="handleAssignRole(scope.row)"
            >
              分配角色
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="mt-2 flex justify-end">
        <el-pagination
          v-model:current-page="searchForm.page"
          v-model:page-size="searchForm.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="userList.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 角色分配对话框 -->
    <el-dialog v-model="roleDialogVisible" title="分配角色" width="500px" destroy-on-close>
      <div v-loading="loadingRole">
        <div class="mb-4 rounded-lg bg-gray-50 p-4">
          <p class="mb-2"><strong>用户名：</strong>{{ selectedUser?.username }}</p>
          <p class="mb-2"><strong>昵称：</strong>{{ selectedUser?.nickname }}</p>
        </div>
        <!-- 角色选择 -->
        <el-form label-width="80px">
          <el-form-item label="角色">
            <el-select
              v-model="selectedRoleIds"
              multiple
              placeholder="请选择角色"
              style="width: 100%"
            >
              <el-option
                v-for="role in roleList"
                :key="role.id"
                :label="role.name"
                :value="role.id"
              >
                <span>{{ role.name }}</span>
                <span class="ml-2 text-xs text-(--el-text-color-secondary)">
                  {{ role.code }}
                </span>
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </div>

      <template #footer>
        <div class="flex justify-end space-x-2">
          <el-button @click="roleDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmAssignRole" :loading="loadingAssign">
            确认分配
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 用户表单对话框 -->
    <el-dialog v-model="userDialogVisible" :title="dialogTitle" width="500px" destroy-on-close>
      <el-form ref="userFormRef" :model="userForm" label-width="100px" :rules="userFormRules">
        <el-form-item label="用户名" prop="username" v-if="!isEditMode">
          <el-input v-model="userForm.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="!isEditMode">
          <el-input v-model="userForm.password" type="password" placeholder="请输入密码" />
        </el-form-item>
        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="userForm.nickname" placeholder="请输入昵称" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userForm.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="userForm.phone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="性别">
          <el-radio-group v-model="userForm.gender">
            <el-radio :label="0">未知</el-radio>
            <el-radio :label="1">男</el-radio>
            <el-radio :label="2">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="状态">
          <el-switch v-model="userForm.status" :active-value="1" :inactive-value="0" />
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="userForm.remark" type="textarea" placeholder="请输入备注" :rows="3" />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="flex justify-end space-x-2">
          <el-button @click="userDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmUserForm" :loading="submitting">
            确认
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { getAllRolesApi } from '@/api/system/permission.api'
import { createUser, getUserById, getUserList, updateUser } from '@/api/system/user.api'
import { to } from '@/utils/promise'
import { Plus } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox, type FormInstance } from 'element-plus'
import { computed, onMounted, reactive, ref } from 'vue'

// 搜索表单
const searchForm = reactive<UserQueryParams>({
  username: '',
  nickname: '',
  page: 1,
  pageSize: 10
})

// 用户列表
const userList = ref<PageResponse<UserFormData>>({
  list: [],
  total: 0,
  page: 1,
  pageSize: 10
})

// 加载状态
const loading = ref(false)
const loadingRole = ref(false)
const loadingAssign = ref(false)

// 选中的用户
const selectedUser = ref<UserFormData | null>(null)
const selectedRows = ref<UserFormData[]>([])

// 角色分配对话框
const roleDialogVisible = ref(false)
const roleList = ref<RoleInfo[]>([])
const selectedRoleIds = ref<number[]>([])

// 用户表单对话框
const userDialogVisible = ref(false)
const userFormRef = ref<FormInstance>()
const submitting = ref(false)
const currentUser = ref<UserFormData | null>(null)
const isEditMode = computed(() => !!currentUser.value)
const dialogTitle = computed(() => (isEditMode.value ? '编辑用户' : '新增用户'))

// 用户表单
const userForm = reactive<any>({
  username: '',
  password: '',
  nickname: '',
  email: '',
  phone: '',
  gender: 0,
  status: 1,
  remark: ''
})

// 表单验证规则
const userFormRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 50, message: '用户名长度在 3 到 50 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  nickname: [
    { required: true, message: '请输入昵称', trigger: 'blur' },
    { min: 2, max: 50, message: '昵称长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  email: [
    {
      pattern: /^[^\s@]+@[^\s@]+\.[^\s@]+$/,
      message: '请输入有效的邮箱地址',
      trigger: 'blur',
      required: true
    }
  ],
  phone: [
    {
      pattern: /^1[3-9]\d{9}$/,
      message: '请输入有效的手机号',
      trigger: 'blur',
      required: true
    }
  ]
}

// 获取用户列表
const fetchUserList = async () => {
  loading.value = true
  const [error, response] = await to(getUserList(searchForm))
  if (error) {
    ElMessage.error('获取用户列表失败')
    return
  }
  userList.value = response || { list: [], total: 0, page: 1, pageSize: 10 }
  loading.value = false
}

// 搜索
const handleSearch = () => {
  searchForm.page = 1
  fetchUserList()
}

// 重置搜索
const resetSearch = () => {
  searchForm.username = ''
  searchForm.nickname = ''
  searchForm.page = 1
  fetchUserList()
}

// 分页变化
const handleSizeChange = (size: number) => {
  searchForm.pageSize = size
  fetchUserList()
}

const handleCurrentChange = (current: number) => {
  searchForm.page = current
  fetchUserList()
}

// 选择变化
const handleSelectionChange = (rows: UserFormData[]) => {
  selectedRows.value = rows
}

// 状态变化
const handleStatusChange = async (row: UserFormData) => {
  try {
    const message = row.status ? '确定要启用该用户吗？' : '确定要禁用该用户吗？'
    await ElMessageBox.confirm(message, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    // TODO: 调用更新用户状态的接口
    ElMessage.success('操作成功')
  } catch (error) {
    row.status = 1 // 恢复原状态
  }
}

// 分配角色
const handleAssignRole = async (user: UserFormData) => {
  selectedUser.value = user

  // 加载所有角色
  await loadRoleList()

  // 加载用户当前的角色
  await loadUserRoles(user.id)

  roleDialogVisible.value = true
}

// 加载角色列表
const loadRoleList = async () => {
  loadingRole.value = true
  const [error, response] = await to(getAllRolesApi())
  if (error) {
    ElMessage.error('获取角色列表失败')
    return
  }
  roleList.value = response || []
  loadingRole.value = false
}

// 加载用户角色
const loadUserRoles = async (userId: number) => {
  const [error, response] = await to(getUserById(userId))
  if (error) {
    ElMessage.error('获取用户角色失败')
    return
  }
  selectedRoleIds.value = response?.roles?.map((role) => role.id) || []
}

// 确认分配角色
const confirmAssignRole = async () => {
  if (!selectedUser.value) return

  loadingAssign.value = true
  const [error] = await to(
    updateUser(selectedUser.value.id, {
      nickname: selectedUser.value.nickname,
      email: selectedUser.value.email,
      phone: selectedUser.value.phone,
      gender: selectedUser.value.gender,
      status: selectedUser.value.status,
      remark: selectedUser.value.remark,
      roleIds: selectedRoleIds.value
    })
  )
  if (error) {
    ElMessage.error('分配角色失败')
    return
  }
  ElMessage.success('分配角色成功')
  roleDialogVisible.value = false
  fetchUserList()
  loadingAssign.value = false
}

// 处理创建用户
const handleCreateUser = () => {
  currentUser.value = null
  // 重置表单
  Object.assign(userForm, {
    username: '',
    password: '',
    nickname: '',
    email: '',
    phone: '',
    gender: 0,
    status: 1,
    remark: ''
  })
  userDialogVisible.value = true
}

// 处理编辑用户
const handleEditUser = (user: UserFormData) => {
  currentUser.value = user
  // 填充表单数据
  Object.assign(userForm, {
    nickname: user.nickname,
    email: user.email || '',
    phone: user.phone || '',
    gender: user.gender || 0,
    status: user.status,
    remark: user.remark || ''
  })
  userDialogVisible.value = true
}

// 确认用户表单提交
const confirmUserForm = async () => {
  if (!userFormRef.value) return

  try {
    await userFormRef.value.validate()
    submitting.value = true

    if (isEditMode.value && currentUser.value) {
      // 更新用户
      const updateData: UserUpdateRequest = {
        nickname: userForm.nickname,
        email: userForm.email,
        phone: userForm.phone,
        gender: userForm.gender,
        status: userForm.status,
        remark: userForm.remark
      }
      await updateUser(currentUser.value.id, updateData)
    } else {
      // 创建用户
      const createData: UserCreateRequest = {
        username: userForm.username,
        password: userForm.password,
        nickname: userForm.nickname,
        email: userForm.email,
        phone: userForm.phone,
        gender: userForm.gender,
        status: userForm.status,
        remark: userForm.remark
      }
      await createUser(createData)
    }

    userDialogVisible.value = false
    // 刷新用户列表
    fetchUserList()
  } catch (error: any) {
    // 表单验证失败或API调用失败
    console.error('用户操作失败:', error)
    if (!error.message?.includes('cancel')) {
      ElMessage.error('操作失败，请重试')
    }
  } finally {
    submitting.value = false
  }
}

// 初始化
onMounted(() => {
  fetchUserList()
})
</script>

<style scoped>
/* 移除了所有自定义样式，改用 Tailwind CSS */
</style>
